import React, { useState, useEffect, forwardRef } from 'react'; //
import cls from 'classnames';
import styles from './index.less';

export interface IOptionProps {
    value?: string | number;
    onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
    checked?: boolean;
    disabled?: boolean;
    size?: 'samll' | 'default' | 'large';
    children?: React.ReactNode;
    labelStyle?: React.CSSProperties;
    [propName: string]: any;
}


const Checkbox = forwardRef((props: IOptionProps) => {
    const { value, checked, labelStyle, children, disabled, onChange } = props;

    const [ischecked, setIsChecked] = useState<boolean | undefined>(false);

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        setIsChecked(!ischecked);
        onChange && onChange(e);
    };

    useEffect(() => {
        if (checked !== ischecked) {
            setIsChecked(checked);
        }
    }, []);

    return (
        <label
            className={cls(`${styles[`checkbox-wrapper`]}`, {
                [`${styles['checkbox-checked']}`]: checked,
                [`${styles['checkbox-disabled']}`]: disabled,
            })}
            style={labelStyle}
        >
            <span className={cls(`${styles[`checkbox`]}`)} >
                <input
                    type="checkbox"
                    value={value}
                    checked={ischecked}
                    className={cls(`${styles[`checkbox-input`]}`)}
                    onChange={handleChange}
                    disabled={disabled}
                />
                <label className={cls(`${styles[`checkbox-inner`]}`)} />
            </span>
            <span className={cls(`${styles[`checkbox-label`]}`)}>{children}</span>
        </label>
    );
});

Checkbox.defaultProps = {
    checked: false
};

export default Checkbox;
